if(typeof(Terminal)=="undefined"){
	Terminal={getConfig:function(){}};
}
if(typeof(GOLBAL_DATA.ModulePermission)=="undefined"){
	GOLBAL_DATA={ModulePermission:{}};
}
var RTQ_TickerTape = function(mod,animSpeed,data,objName,cfg){
    this.mod = mod;
    this.objName = objName; 
    this.ctn;
    var savedData = (objName=='rtt1')?Terminal.getConfig('TickerTape1'):Terminal.getConfig('TickerTape2');
    this.data = savedData ? savedData.tickers : data;
    this.tickers;
    this.tickerMenu;
    this.tickersRc = [];
    this.tickerPIDs = [];
    this.tickerMenuWidth = 142;
    this.maxTicker = 30;
    this.cloneTickers = null;
    this.addPN = null;
    this.stopAnim = true;
    this.AnimTimer = -1;
    this.currentEditTk = null;
    this.animSpeed = ((10-animSpeed)>0)?10-animSpeed:1;
    this.tickerMenuTimer = null;
    this.needCloned = true;
    this.maxScroll = 0;
    this.qs_server = 'http://qt.morningstar.com/switchservice/qtswitch.ashx?symbol=';
	this.tValidation = new tickerValidation(5,this.objName,"tValidation");   // ticker validation object
	this.isHide = false;
	this.autocpid="";
	this.submitEditTicker;
	this.submitAddTicker;
	this.cfg=$.extend({mouseoverAble:true},cfg)
    this.init(mod);
};
RTQ_TickerTape.prototype = {
    init:function(mod){
        var that = this;
        this.ctn = $(mod).find('div.rtt-ctn');
        this.tickerMenu = this.createTickersMenu();
        this.tickers = this.ctn.children('ul');
        this.createTickers(this.data, false);
        this.createAddTickerPN();

        //this.starRoll();
        this.ctn[0].scrollLeft = 0;
        //event
        if (this.cfg.mouseoverAble) {
            this.ctn.bind('mouseover', this, this.stopRoll).bind('mouseout', this, function(){
                that.starRoll.call(that)
            });
            this.tickers.find('li').mouseover(function(e){
                that.tkShowTickerMenu.call(that, $(this));
            }).mouseout(function(e){
                that.hideTickerMenu.call(that);
            });
            $(window).resize(function(){
                that.needCloned = true;
                that.starRoll();
            })
        }
    },
    rebuild:function(){
        var that = this;
        //this.needCloned = true;
        this.starRoll();
    },
    getMaxScroll:function(){
        return this.ctn[0].scrollWidth;
    },
    updateData: function(gKey,d){
        if(this.checkSubscribe(gKey)<0){return;}
        var tks = this.getTicker(gKey);
        if(tks){
            this.updateTicker(gKey, tks);
        }else{
            this.addTicker(gKey);
        }
    },
    subscribeTicker:function(tks, needSave){
        if(this.tickersRc.length>=this.maxTicker){
            alert(QS_Lang.tickertape["tp_overmaxprompt"]);
            return;
        }
        for (var i = 0, l = tks.length; i < l; i++) {
            if (this.checkSubscribe(tks[i]) >= 0) {
                continue;
            }
		    this.addTicker(tks[i]);
            this.tickersRc.push(tks[i]);
            this.tickerPIDs.push(gData[tks[i]].performanceId);
        }
        needSave = needSave===false?false:true;
        if (needSave) {
            this.saveConfig();
        }
        //console.log($.toJSON(s)); 
    },
    unSubscribeTicker:function(gkey){
        this.tickersRc.splice(this.checkSubscribe(gkey),1);
        var pid = gData[gkey].performanceId;
        for(var i=0;i<this.tickerPIDs.length;i++){
            if(this.tickerPIDs[i] == pid){
                this.tickerPIDs.splice(i,1);
            }
        }
		this.tValidation.unSubscribe(gkey);
        this.saveConfig();
    },
    checkSubscribe:function(o){
        for(var i=0;i<this.tickersRc.length;i++){
            if(this.tickersRc[i]==o){
                return i;
            }
        }
        return -1;
    },
    preSubscribeTicker:function(gkeyList, needSave){
		if(!gkeyList || !gkeyList.length) return;
		this.subscribeTicker(gkeyList, needSave);
    },
    show:function(){
        if (this.isHide) {
            $(this.mod).show();
            this.tValidation.checkTickers(this.tickerPIDs);
        }
    },
    hide:function(){
        $(this.mod).hide();
        this.tValidation.unSubscribe(this.tickerPIDs); // unsubscribe ticker
        this.isHide = true;
    },
    addTicker:function(gKey){
        var that = this;
        var tks = this.getTicker(gKey);
        if(tks){
            this.updateTicker(gKey, tks);
            return;
        }
        var tk = $('<li></li>');
        tk.data('LastPrice','--').data('Chg','--').data('Chgpc','--');
        this.createTickerDOM(tk,gKey);
        //event
		if(this.cfg.mouseoverAble){
			tk.mouseover(function(e){
            that.tkShowTickerMenu.call(that,$(this));
        }).mouseout(function(e){
            that.hideTickerMenu.call(that);
        });
		}
        if(this.cloneTickers){
            tk.insertBefore(this.cloneTickers.eq(0));
        }else{
            this.tickers.append(tk);
        }
        this.rebuild();
    },
    getTicker:function(keyid){
        var tks = this.tickers.children('[keyid="'+keyid+'"]');
        if(tks.length>0){
            return tks;
        }else{
            return null;
        }
    },
    updateTicker:function(gkey,tks){
        var that = this;
        tks.each(function(i){
            that.createTickerDOM($(this),gkey);
            //tk.show();
        });
        //this.rebuild();
    },
    createTickerDOM:function(tk,gKey){
		var tkObj = gData[gKey];
		var tkObj_price = push.proxy.getMarketQuoteData(gKey);
		if(!tkObj||!tkObj_price) return;
        if(tkObj.exch){tk.attr('Exch',tkObj.exch);}
        var lp = typeof tkObj_price.LastPrice != 'undefined'&&typeof tkObj_price.LastPrice.value != 'undefined'?tkObj_price.LastPrice.value.toFixed(2):tk.data('LastPrice');
        var chg = typeof tkObj_price.Chg != 'undefined'&&typeof tkObj_price.Chg.value != 'undefined'?tkObj_price.Chg.value.toFixed(2):tk.data('Chg');
        var chgpc = typeof tkObj_price['Chg%'] != 'undefined'&&typeof tkObj_price['Chg%'].value != 'undefined'?tkObj_price['Chg%'].value.toFixed(2):tk.data('Chgpc');
        var color = (chg>=0)?'up':((chg<0)?'down':'def');
        //tk.data('LastPrice',lp).data('Chg',chg).data('Chgpc',chgpc); //bug in IE
        tk.data('LastPrice',lp);
        tk.data('Chg',chg);
        tk.data('Chgpc',chgpc);
        tk.attr('keyid',gKey).attr('class',color).html('<strong><a>'+tkObj.ticker+'</a></strong><cite>'+(lp||'--')+'<span>'+(chg||'--')+'('+ (chgpc||'--') +'%)</span></cite>');
    },
    deleteTicker:function(keyid){
        this.tickers.find('[keyid="'+keyid+'"]').remove();
		this.unSubscribeTicker(keyid); // unsubscribe ticker.
        this.needCloned = true;
        this.starRoll();
    },
    refreshTicker:function(tk,dt){
        tk.style.background = 'red';
        setTimeout(function(){tk.style.background = '';},500);
    },
    createTickers:function(data, needSave){
        var tks = '';
        for(var i=0;i<data.length;i++){
            tks += data[i] + ','
            if(i==data.length-1){
                this.needCloned = true;
            }
        }
        var self = this;
		setTimeout(function(){
			self.tValidation.checkTickers(tks, function(o){
				self.preSubscribeTicker(o, needSave);
			})
		},0);
    },
    createTickersMenu:function(){
        var that = this,qslang=QS_Lang.tickertape;
        var autocpid = 'autobox_'+this.mod.id;
        var autocpddlid = 'autobox_ddl_'+this.mod.id;
        var div = document.createElement('div');
        div.className = 'rtt-tkmenu';
        div.innerHTML = '<div class="rtt-tkmenu-inner"><div class="rtt-editpn"><input type="text" value="" class="qs-ui-ipt" idkey="autoBox" id="' + autocpid + '"/><a class="qs-ui-btn go" href="javascript:void(0)">'+qslang["tp_mticker_save"]+'</a><div id="' + autocpddlid + '" class="autocpddl"></div></div><a href="?" class="rtt-editbtn">'+qslang["tp_mticker_edit"]+'</a><a href="?" class="rtt-delbtn">'+qslang["tp_mticker_del"]+'</a><a href="?" class="cmd" pms="9">'+qslang["tp_mticker_quote"]+'</a><a href="?" class="cmd" pms="2">'+qslang["tp_mticker_news"]+'</a><a href="?" class="cmd" pms="6">'+qslang["tp_mticker_l2"]+'</a></div>';
        $(this.mod).append(div);
        //permission
        var lnkMods = [9, 2, 6];
        for (var i = 0; i < lnkMods.length; i++) {
            if ($.inArray(lnkMods[i], GOLBAL_DATA.ModulePermission) < 0) {
                $(div).find("[pms='" + lnkMods[i] + "']").hide();
            }
        }
        
        //autoCP
        var callback = this.objName+".autoCPselect";     
		if ($("#"+autocpid).length > 0) {
			this.autocpid = autocpid;
			GB_qsAutoCompleteBox.subscription(autocpid,function(data){
				that.autoCPselect(data);
				} ,{needClear:true,reCall:true});
        }
        //event
        var rtteditpn = $(div).find('.rtt-editpn');
        var rtcctrlinput = $(div).find('.qs-ui-ipt');
        var submitEditTicker = function(){
            if(rtcctrlinput.val().length>0||typeof(rtcctrlinput.attr("realVal"))!="undefined"){
                var val = (typeof(rtcctrlinput.attr("realVal"))!="undefined"&&rtcctrlinput.attr("realVal") !="")?rtcctrlinput.attr("realVal"):rtcctrlinput.val();
//                var sn = val.split(':')[0].toUpperCase();
//                var name = val.split(':')[1].toUpperCase();
				var oldKey = that.currentEditTk.attr('keyid');	
				that.tValidation.checkTickers(val,function(o){
                    
                    if (typeof(that.hideLoading) == 'function' && typeof(o) != 'undefined' && o.length == 0) {
                        that.hideLoading();
                    }
					if(!o || !o.length ||o.length < 1) return false;
					if (that.checkSubscribe(o[0]) >= 0) {
               		 	return;
            		}
					that.updateTicker(o[0],that.getTicker(oldKey)); // update the ui for new ticker.
					that.unSubscribeTicker(oldKey); // unsubscribe the old ticker;
					that.preSubscribeTicker(o);
				});
                //checkTickerInfo(val, that.objName + '.preSubscribeTicker');
                that.hideTickerMenu();
				rtcctrlinput.val("");
            }else{
                rtcctrlinput.focus();
            }
            return false;
        };
		this.submitEditTicker=submitEditTicker;
        rtcctrlinput.click(function(){$(this).val('');}).keyup(function(e){
            if(e.keyCode==13){
                submitEditTicker();
            }
        });
        $(div).find('.rtt-editbtn').click(function(){
            if(rtteditpn.css('display')=='none'){
                rtteditpn.show();
            }else{
                rtteditpn.hide();
            }
            that.setTickerMenuPos.call(that,$(that.currentEditTk));
            return false;
        });
        $(div).find('.go').click(submitEditTicker);
        $(div).find('.rtt-delbtn').click(function(){
            that.deleteTicker.call(that,that.currentEditTk.attr('keyid'));
            $(that.tickerMenu).hide();
            return false;
        });
        $(div).mouseover(function(e){
            that.showTickerMenu.call(that);
            that.ctn.stop();
        }).mouseout(function(e){
			if(!GB_qsAutoCompleteBox.listVisible()){
				that.hideTickerMenu.call(that);
           	 	that.starRoll.call(that);
			}
        });
        $(div).find('a.cmd').click(function(e){
            if(workspaceManager&&getDefaultProfileByType){
                var type = $(this).attr('pms');
				var exch=that.currentEditTk.attr('Exch');
				var gKey=that.currentEditTk.attr('keyid');
			
                var tk = exch+':'+gKey.split(':')[1];
                var profile = getDefaultProfileByType(type);
                if(gData[gKey]&&gData[gKey].performanceId){
					tk=gData[gKey].performanceId;
				}
				workspaceManager.addWidgetToCurrentWs(type, tk, profile);
            }
            return false;
        });
        
        return div;
    },
    autoCPselect:function(o){
		if(o!="recall-qs-auto"){
			$(this.tickerMenu).find('.qs-ui-ipt').attr("realVal",o);
			this.submitEditTicker();
			this.starRoll.call(this);
		}else{
			this.hideTickerMenu();
			this.starRoll.call(this);
		}
        
    },
    showTickerMenu:function(){
        if(this.tickerMenuTimer){
            clearTimeout(this.tickerMenuTimer);
            this.tickerMenuTimer = null;
        }
        var that = this;
        this.tickerMenuTimer = setTimeout(function(){
            $(that.tickerMenu).show();
            that.setTickerMenuPos.call(that,$(that.currentEditTk));
        },50);
        if(this.currentEditTk){
            this.currentEditTk.addClass('on');
        }
    },
    tkShowTickerMenu:function(tk){
		if(this.currentEditTk!=null&&tk[0].innerHTML==this.currentEditTk[0].innerHTML){
		 	this.currentEditTk = tk;
			this.showTickerMenu();
			return;
		}else{
			this.currentEditTk = tk;
		}
		GB_qsAutoCompleteBox.hideBox();
		$(this.tickerMenu).hide();
      //  this.showTickerMenu();
       // $(this.tickerMenu).find('.rtt-editpn').hide();
    },
    hideTickerMenu:function(){
        if(this.tickerMenuTimer){
            clearTimeout(this.tickerMenuTimer);
            this.tickerMenuTimer = null;
        }
        var that = this;
        this.tickerMenuTimer = setTimeout(function(){
			if(!GB_qsAutoCompleteBox.listVisible()){
				GB_qsAutoCompleteBox.hideBox();
				$(that.tickerMenu).hide();
			}
        },200);
        if(this.currentEditTk){
            this.currentEditTk.removeClass('on');
        }
    },
    setTickerMenuPos:function(offsetparent){
		var t = $(offsetparent);
		var diffHeight=48-t.offset().top;
		var isUp = diffHeight<0;
        var top =-(this.tickerMenu.offsetHeight-$(offsetparent)[0].offsetTop-25);
		if(!isUp){
			//top =this.tickerMenu.offsetHeight+t.offset().top;
		}
        $(this.tickerMenu).css({
            'left':(offsetparent.offset().left<0)?0:(((offsetparent.offset().left+$(this.tickerMenu).width())>this.ctn.width())?this.ctn.width()-$(this.tickerMenu).width():offsetparent.offset().left)+'px',
            'top':top+'px'
            //'width':Math.max($(offsetparent).width(),this.tickerMenuWidth)+10+'px'
        });
    },
    createAddTickerPN:function(){
        var that = this;
        var autocpid = 'autobox_add'+this.mod.id;
        var autocpddlid = 'autobox_ddladd_'+this.mod.id;
        this.addPN = $('<div class="rtt-addpn"><input type="text" value="" class="qs-ui-ipt" idkey="autoBox" id="'+autocpid+'"/><a class="qs-ui-btn go" href="javascript:void(0)">'+QS_Lang.tickertape["tp_mticker_add"]+'</a><div id="'+autocpddlid+'" class="autocpddl"></div></div>');
        $(this.mod).append(this.addPN);
        var callback = this.objName+".autoCPselect_add";   
		if ($("#"+autocpid).length > 0) {
           //Util.createAutoCompleteBox(autocpid,autocpddlid,"USA","EN-US",8,false,callback); 
		   this.autocpid = autocpid;
		   GB_qsAutoCompleteBox.subscription(autocpid,function(data){that.autoCPselect_add(data)},{needClear:true,reCall:true});
        }	
		
        var addlnk = $(this.mod).find('.rtt-addlnk');
        var addpn = this.addPN;
        var addinput = this.addPN.find('.qs-ui-ipt');
        var submitAddTicker = function(){
            if(addinput.val().length>0||addinput.attr("realVal")!=""){
                //checkTickerInfo(addinput.val(),that.objName + '.preSubscribeTicker');//preAdd
                //that.subscribeTicker(addinput.val().split(':')[0],addinput.val().split(':')[1]);
				that.tValidation.checkTickers((typeof(addinput.attr("realVal"))!="undefined"&&addinput.attr("realVal")!="")?addinput.attr("realVal"):addinput.val(),function(o){that.preSubscribeTicker(o);});
                that.needCloned = true;// for animate
                addpn.hide();
				addinput.val("");
            }else{
                addinput.select();
            }
            return false;
        };
		this.submitAddTicker=submitAddTicker;
        addinput.click(function(){$(this).select();}).keyup(function(e){
            if(e.keyCode==13){
                submitAddTicker();
            }
        });
        addlnk.click(function(){
            if(addpn.css('display')=='none'){
                addpn.show();
            }else{
                addpn.hide();
            }
            return false;
        });
        addpn.find('.go').click(submitAddTicker);
    },
    autoCPselect_add:function(o){
		if(o!="recall-qs-auto"){
			//this.addPN.find('.qs-ui-ipt').val(o);
			//$(this.tickerMenu).find('.qs-ui-ipt').val(o);
			this.addPN.find('.qs-ui-ipt').attr("realVal",o)
			this.submitAddTicker();
			this.starRoll.call(this);
		}else{
			this.hideTickerMenu();
			this.starRoll.call(this);
		}
    },
    roll:function(e){
         var that = e?e.data:this;
         if (that) {
             that.ctn.animate({
                 scrollLeft: '+=20'
             }, {
                 duration: that.animSpeed * 100,
                 easing: 'linear',
                 step: function(){
                 },
                 complete: function(){
                     if (that.ctn[0].scrollLeft >= that.tickersRc.length * 202 - 10) {
                         that.ctn[0].scrollLeft = 0;
                     }
                     that.roll(e || null);
                 }
             });
         }
        /*if (that.AnimTimer) {
            window.clearTimeout(that.AnimTimer);
            that.AnimTimer = -1;
        }
        if(that.ctn[0].scrollLeft>=that.cloneTickers[0].offsetLeft){
            that.ctn[0].scrollLeft = 0;
        }
        that.ctn[0].scrollLeft +=2;
        that.AnimTimer = window.setTimeout(function(){
            that.roll.call(that);
        }, that.animSpeed*10);
        */
    },
    starRoll:function(e,needClone){
        this.ctn.stop();
        var that = this;
        this.tickers.css('width', this.tickers.children('li').length * 202);
        if(this.ctn[0].scrollWidth<=$(document.body).width()||(this.cloneTickers&&this.cloneTickers[0].offsetLeft<=$(document.body).width())){
            if(this.cloneTickers){
                this.cloneTickers.remove();
                this.cloneTickers = null;
            }
            this.ctn[0].scrollLeft = 0;
            return;
        }
        if(this.needCloned){
            if(this.cloneTickers){
                this.cloneTickers.remove();
                this.cloneTickers = null;
            }
            this.maxScroll = this.ctn[0].scrollWidth;
            
            this.cloneTickers = this.tickers.children('li:lt(20)').clone().appendTo(this.tickers).mouseover(function(e){
				if (that.cfg.mouseoverAble){
					that.tkShowTickerMenu.call(that,$(this));
				}
            }).mouseout(function(e){
                that.hideTickerMenu.call(that);
            });
            this.needCloned = false;
        }
        this.roll(e);
    },
    stopRoll:function(e){
        e.data.ctn.stop();
        /*if (this.AnimTimer) {
            window.clearTimeout(this.AnimTimer);
            this.AnimTimer = -1;
        }*/
    },
    saveConfig:function(){
        /*
        var savedData = (this.objName=='rtt1')?Terminal.getConfig('TickerTape1'):Terminal.getConfig('TickerTape2');
        if(savedData && this.tickerPIDs.toString() == savedData.tickers.toString()){
            return;
        }*/
       
        //save order
        var tks = [], gkey, pid;
        var tkDoms = this.tickers.children('li').each(function(i){
            gkey = this.getAttribute('keyid');
            pid = gData[gkey].performanceId;
            if($.inArray(pid, tks)<0){
                tks.push(pid);
            }
        });
        if (this.objName == 'rtt1') {
            Terminal.setConfig({
                TickerTape1: {
                    tickers: tks
                }
            });
        }
        else {
            Terminal.setConfig({
                TickerTape2: {
                    tickers: tks
                }
            });
        }
    }
};